<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :multiple="true"
      name="upfile"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :file-list="imageList"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadSectionFile"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-image-viewer
      v-if="dialogVisible"
      :on-close="closeViewer"
      :url-list="value"
    />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import {uploadFile} from '@/api/common/index'
export default {
  components: {
    ElImageViewer
  },
  props: {
    value: {
      default: () => [],
      type: Array
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      uploadUrl: '/api/common/back/file',
      // imageArray: [],
      errorImg: ''
    }
  },
  computed: {
    imageList() {
      const res = []
      if (this.value) {
        const imageArray = this.value
        for (let i = 0; i < imageArray.length; i++) {
          res.push({ url: imageArray[i], response: imageArray[i] })
        }
      }
      this.$emit('input', this.value)
      return res
    }
  },
  methods: {
    uploadSectionFile(params){
        const _this=this
        const index=_this.value.length
        const postParam=new FormData()
        postParam.append("upfile",params.file)
        uploadFile(postParam).then(res=>{
            _this.value.splice(index,0,res)
        })
    },
    // 图片上传
    handleUploadSuccess(response, file, fileList) {
      const pics = fileList.map(file => {
        return file.response
      })
      this.$emit('input', pics)
    },
    // 限制图片上传大小
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleRemove(file, fileList) {
      const array = fileList.map(file => {
        return file.response
      })
      this.$emit('input', array)
    },
    handlePictureCardPreview(file) {
      this.dialogVisible = true
    },
    closeViewer() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss">
</style>
